package acme.routing.server;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ws.tracking.*;

public class RoutingEngineImpl
{
  public List<Vehicle> computeAllRoutes(List<Vehicle> currentRoutes, List<Order> newOrders) throws RoutingException
  {

    if (newOrders == null || newOrders.size() == 0)
    {
      return currentRoutes;
    }
    if (currentRoutes == null || currentRoutes.size() == 0)
    {
      throw new RoutingException();
    }

    try
    {
      // create a map with live references to each vehicle's current routes
      Map<Integer, List<Stop>> m = new HashMap<Integer, List<Stop>>();
      for (int i = 0; i < currentRoutes.size(); ++i)
      {
        ArrayList<Stop> a = new ArrayList<Stop>();
        List<Stop> currentRoute = currentRoutes.get(i).getCurrentRoute();
        m.put(i, currentRoute);
      }
      
      for (int i = 0; i < newOrders.size(); ++i)
      {
        Order order = newOrders.get(i);
        
        // add the new order to the vehicle with the fewest stops
        // already defined
        int min = minIndex(m);
        Stop s = new Stop();
        s.setLocation(order.getSrc());
        s.getPickups().add(order);
        m.get(min).add(s);
        s = new Stop();
        s.setLocation(order.getDst());
        s.getDeliveries().add(order);
        m.get(min).add(s);
//        m.get(min).add(new Stop(order.getSrc(), new Order[]{order}, new Order[0] ));
//        m.get(min).add(new Stop(order.getDst(), new Order[0], new Order[]{order} ));
      }
      
      return currentRoutes;
    } 
    catch (Exception e)
    {
      throw new RoutingException();
    }
  
  }
  
  private static int minIndex(Map<Integer, List<Stop>> m)
  {
    int minIndex = 0;
    int minLength = m.get(0).size();
    for (Integer i : m.keySet())
    {
      if (m.get(i).size() < minLength)
      {
        minLength = m.get(i).size();
        minIndex = i;
      }
    }
    
    return minIndex;
  }

}
